﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.Office.OneNote.Interop;

namespace Microsoft.Office.OneNote
{
    internal sealed class OneNoteHierarchyObjectStorage : OneNoteObjectStorage<OneNoteHierarchyObject>
    {
        internal OneNoteHierarchyObjectStorage(IOneNoteHierarchy owner)
        {
            this.Owner = owner;
        }

        public IOneNoteHierarchy Owner
        {
            get;
            private set;
        }

        public T Open<T>(string path, OneNoteObjectId relativeTo, bool openExisting)
            where T : OneNoteHierarchyObject
        {
            CreateHierarchyType type = CreateHierarchyType.None;

            if (!openExisting)
            {
                type = OneNoteObjectFactory.GetHierarchyType(typeof(T));
            }

            OneNoteObjectId id = OneNoteApplication.Current.OpenHierarchy(path, relativeTo, type);

            Owner.Update();

            return (T)this[id];
        }

        public bool Delete(OneNoteHierarchyObject obj)
        {
            if (Contains(obj))
            {
                OneNoteApplication.Current.DeleteHierarchy(obj.ObjectId, obj.LastModifiedTime);
                Owner.Update();

                return true;
            }

            return false;
        }


        public void UpdateHierarchy(OneNoteHierarchy hierarchy)
        {
            foreach (var child in GetCollection().Cast<OneNoteHierarchyObject>())
            {
                child.Hierarchy = hierarchy;
            }
        }

        protected override void InitializeStoredObject(OneNoteHierarchyObject obj)
        {
            base.InitializeStoredObject(obj);

            obj.Parent = (Owner as OneNoteHierarchyObject);
            obj.Hierarchy = Owner.Hierarchy;
        }
    }
}
